import { Algorithm } from "../types"

// 数据模型定义
interface MPLPNode {
  id: any
  type: string
  attributes: Record<string, any>
}

interface MPLPEdge {
  source: any
  target: any
  type?: string
  weight?: number
  attributes: Record<string, any>
}

interface MPLPGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
}

// 定义时序图数据结构
interface TemporalGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
  timestamp: string
}

// 修改任务状态枚举
enum TaskStatus {
  PENDING = "PENDING",
  RUNNING = "RUNNING", 
  COMPLETED = "COMPLETED",
  FAILED = "FAILED"
}

// 修改接口定义以匹配后端schema
interface BankTransactionNode {
  node_id: number;
  account_type: string;
  risk_score: number;
  transaction_volume: number;
  timestamp: string;
}

interface BankRiskInputParams {
  transaction_edges: Array<Array<Array<any>>>;  // [时间步[[from_node, to_node, amount], ...]]
  nodes_info: BankTransactionNode[];
  time_window?: number;
  risk_threshold?: number;
  community_count?: number;
  alpha?: number;
}

interface TimeStepRiskResult {
  timestamp: string;
  risk_communities: number[];
  risk_scores: number[];
  alert_nodes: number[];
  community_risk_levels: ('LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL')[];
}

interface BankRiskOutputParams {
  results: TimeStepRiskResult[];
  overall_risk_score: number;
  high_risk_patterns: Array<Record<string, any>>;
  risk_evolution: number[];
  algorithm_parameters: Record<string, any>;
}

interface InputParams {
  input_params: BankRiskInputParams;
}

interface OutputParams {
  output_params: BankRiskOutputParams;
}

interface AlgorithmRequest {
  task_id: string;
  task_callback_url?: string;
  input_params: InputParams;
}

interface AlgorithmResponse {
  task_id: string;
  task_callback_url?: string;
  task_status: TaskStatus;
  task_progress: number;
  task_logs?: string;
  error_message?: string;
  output_params: OutputParams;
  metrics: any[]; // 这里可以根据Chart类型进一步定义
}

// 修改算法实现
export const BankRiskService: Algorithm = {
  name: "银行风险分析算法",
  description: "基于图结构和时序分析的银行交易风险评估算法",
  configOptions: [
    {
      id: "time_window",
      label: "时间窗口大小",
      type: "number",
      defaultValue: 10,
      placeholder: "请输入时间窗口大小(默认10)"
    },
    {
      id: "risk_threshold",
      label: "风险阈值",
      type: "number",
      defaultValue: 0.7,
      placeholder: "请输入风险阈值(0-1之间)"
    },
    {
      id: "community_count",
      label: "风险社区数量",
      type: "number",
      defaultValue: 5,
      placeholder: "请输入要划分的社区数量"
    },
    {
      id: "alpha",
      label: "时序平滑参数",
      type: "number",
      defaultValue: 0.8,
      placeholder: "请输入时序平滑参数(0-1之间)"
    },
    {
      id: "nodes_info",
      label: "节点信息",
      type: "textarea",
      placeholder: `请输入JSON格式的节点信息列表，例如：
[
  {
    "node_id": 1,
    "account_type": "个人账户",
    "risk_score": 0.3,
    "transaction_volume": 10000,
    "timestamp": "2024-03-20T10:00:00"
  }
]`
    },
    {
      id: "transaction_edges",
      label: "交易边信息",
      type: "textarea",
      placeholder: `请输入JSON格式的交易边列表，例如：
[
  [
    [1, 2, 5000],
    [2, 3, 3000]
  ]
]`
    }
  ],

  execute: async (config) => {
    try {
      const taskId = `bank_risk_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
      
      let nodesInfo;
      let transactionEdges;
      
      try {
        nodesInfo = JSON.parse(config.nodes_info);
        transactionEdges = JSON.parse(config.transaction_edges);
      } catch (e) {
        throw new Error("输入数据必须是有效的JSON格式");
      }

      const requestData = {
        task_id: taskId,
        input_params: {
          transaction_edges: transactionEdges,
          nodes_info: nodesInfo,
          time_window: Number(config.time_window) || 10,
          risk_threshold: Number(config.risk_threshold) || 0.7,
          community_count: Number(config.community_count) || 5,
          alpha: Number(config.alpha) || 0.8
        }
      };

      // 创建任务
      const createResponse = await fetch("http://172.16.4.151:1122/api/bank_risk/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData)
      });

      if (!createResponse.ok) {
        const errorData = await createResponse.json();
        throw new Error(errorData.detail || "创建任务失败");
      }

      // 执行任务
      const executeResponse = await fetch(`http://172.16.4.151:1122/api/bank_risk/execute/${taskId}`, {
        method: "POST"
      });

      if (!executeResponse.ok) {
        const errorData = await executeResponse.json();
        throw new Error(errorData.detail || "执行任务失败");
      }

      // 轮询获取结果
      let result;
      let attempts = 0;
      const maxAttempts = 60;

      while (attempts < maxAttempts) {
        const getResultResponse = await fetch(`http://172.16.4.151:1122/api/bank_risk/result/${taskId}`);
        
        if (!getResultResponse.ok) {
          const errorData = await getResultResponse.json();
          throw new Error(errorData.detail || "获取结果失败");
        }

        result = await getResultResponse.json();
        
        if (result.task_status === "COMPLETED") {
          break;
        } else if (result.task_status === "FAILED") {
          throw new Error(result.error_message || "任务执行失败");
        }

        await new Promise(resolve => setTimeout(resolve, 1000));
        attempts++;
      }

      if (attempts >= maxAttempts) {
        throw new Error("任务执行超时");
      }

      const outputParams = result.output_params;
      
      // 生成结果摘要
      const resultText = `风险分析完成：
总体风险分数: ${outputParams.overall_risk_score.toFixed(2)}
分析时间步数: ${outputParams.results.length}
识别出的高风险模式数: ${outputParams.high_risk_patterns.length}

风险演化趋势:
${outputParams.risk_evolution.map((score: number, index: number) => 
  `时间步${index + 1}: ${score.toFixed(2)}`
).join('\n')}

高风险节点分布详情:
${outputParams.results.map((step: TimeStepRiskResult, index: number) => {
  const highRiskNodes = step.alert_nodes.map((nodeId: number, idx: number) => {
    const nodeInfo = nodesInfo.find((node: BankTransactionNode) => node.node_id === nodeId);
    const riskScore = step.risk_scores[step.risk_communities.findIndex(id => id === nodeId)];
    return `    节点${nodeId}(${nodeInfo?.account_type || '未知账户'}) - 风险分数: ${riskScore?.toFixed(2) || 'N/A'}`;
  }).join('\n');
  
  return `时间步${index + 1} (${step.timestamp}):
  发现${step.alert_nodes.length}个高风险节点:
${highRiskNodes}
  风险等级: ${step.community_risk_levels[index]}
  ---------------`;
}).join('\n')}

建议关注事项:
${outputParams.high_risk_patterns.map((pattern: Record<string, any>, index: number) => 
  `${index + 1}. ${pattern.description || '发现异常交易模式'}`
).join('\n')}`;

      return {
        result: resultText,
        steps: [],
        executionTime: 0,
        details: outputParams
      };
    } catch (e: any) {
      console.error("银行风险分析执行出错:", e);
      throw e;
    }
  }
}; 